import { defineStore } from 'pinia'
import { apiDoLogin, apiGetInfo } from '@/api/user'
import { type User } from '@/model/user'
import { ElMessage } from 'element-plus'

interface State extends User {
  token: string
}

export const UserState = defineStore('userState', {
  state: (): State => ({
    uid: 0,
    realname: 'Eduardo',
    phone: '12345678910',
    gender: 1,
    building: '1栋',
    room: '101',
    residentNature: '其他',
    role: 1,
    token: '',
  }),

  getters: {},

  actions: {
    async login(phone: string, password: string) {
      // 登录
      try {
        this.token = await apiDoLogin(phone, password)

        // 获取用户信息
        const userInfo: User = await apiGetInfo()
        this.uid = userInfo.uid
        this.realname = userInfo.realname
        this.gender = userInfo.gender
        this.phone = userInfo.phone
        this.role = userInfo.role
        this.building = userInfo.building
        this.room = userInfo.room
        this.residentNature = userInfo.residentNature
        return Promise.resolve()
      } catch (error: unknown) {
        if (error instanceof Error) {
          ElMessage.error(error.message)
        } else {
          console.log(error)
          ElMessage.error('未知错误')
        }
        return Promise.reject(error)
      }
    },
  },
})
